package com.magictower.primary.utils;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author kejunzhan
 * @since 2017/12/18
 */

public class SystemInfoUtils {
    /**
     * 判断一个服务是否运行
     *
     * @param context
     * @param className
     * @return
     */
    public static boolean isServiceRunning(Context context, String className) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningServiceInfo> infos = am.getRunningServices(200);//200个进程
        for (RunningServiceInfo info : infos) {
            if (className.equals(info.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 返回进程数
     *
     * @param context
     * @return
     */
    public static int getProcessCount(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> infos = am.getRunningAppProcesses();
        return infos.size();
    }

    /**
     * 获取可用内存
     *
     * @param context
     * @return
     */
    public static long getAvailMem(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo memoryInfo = new MemoryInfo();
        //获取内存的基本信息
        am.getMemoryInfo(memoryInfo);
        //获取可用内存
        return memoryInfo.availMem;
    }

    public static long getTotalMem(Context context) {
        /*
         * 这个地方不能直接跑到低版本的手机上面 MemTotal: 344740 kB "/proc/meminfo"
         */
        try {
            // "/proc/meminfo"是配置文件路径
            FileInputStream fis = new FileInputStream(new File("/proc/meminfo"));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            String readLine = reader.readLine();
            StringBuffer res = new StringBuffer();
            for (char c : readLine.toCharArray()) {
                if (c >= '0' && c <= '9') {
                    res.append(c);
                }
            }
            return Long.valueOf(res.toString()) * 1024;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
